﻿using Adp;
using Microsoft.AspNetCore.Mvc;
using Yqd.Models;
using Yqd.Controllers.Filter;
using Adp.Common;
using System.Linq;
using System;
using Yqd.Core;
using System.Collections.Generic;
using Newtonsoft.Json.Linq;
using Yqd.Enm;
using System.Linq.Expressions;
using Newtonsoft.Json;

namespace Yqd.Controllers
{
    [Area("Yqd")]
    public class WxSpecialSuperviseController : Controller
    {
        YqdContext ctx;
        DdService ddService;

        public WxSpecialSuperviseController(YqdContext ctx, DdService ddService)
        {
            this.ctx = ctx;
            this.ddService = ddService;
        }

        [User]
        public ActionResult GetList()
        {
            var SuperviseID = Form.GetInt("SuperviseID");
            var supervise = ctx.Yqd_SpecialSupervise.FirstOrDefault(it => it.SuperviseID == SuperviseID);
            if (supervise == null)
            {
                return this.ToJson(new
                {
                    success = true,
                    data = new List<object>()
                });
            }
            var TaskName = "";
            var TaskID = 0;
            JObject Targets = null;
            var task = ctx.Yqd_SpecialTask.FirstOrDefault(it => it.TaskID == supervise.TaskID);
            if (task != null)
            {
                TaskID = task.TaskID;
                TaskName = task.Name;
                supervise.SNo = task.TaskCode + supervise.SNo;
            }
            var f = ctx.Yqd_SpecialTemplate.FirstOrDefault(it => it.TemplateID == supervise.TemplateID);
            var Fields = new JArray();
            var oFields = new JObject();
            if (f != null)
            {
                if (f.Fields.HasValue()) Fields = JArray.Parse(f.Fields);
                if (f.oFields.HasValue()) oFields = JObject.Parse(f.oFields);
            }
            if (supervise.TemplateData.HasValue())
            {
                Targets = JObject.Parse(supervise.TemplateData);
            }
            var data = new List<object>();
            if (Targets != null)
            {
                foreach (var o in Fields)
                {
                    var key = o["FieldID"].ToString();
                    data.Add(new
                    {
                        text = o["Name"]?.ToString() ?? "",
                        value = Targets[key]?.ToString() ?? ""
                    });
                }
            }
            var dept = ctx.Yqd_Unit.Select(it => new { it.UnitCode, it.Name }).ToList();
            var scheme = ctx.Yqd_Scheme.Where(it => it.ItemID == SuperviseID && it.ItemType == 事项类型.专项交办).ToList();
            var a = ctx.Yqd_Assign.FirstOrDefault(it => it.ItemID == SuperviseID && it.ItemType == 事项类型.专项交办);
            var sm = scheme.Where(it => it.CheckStatus != 审核状态.退回);
            var plan = ctx.Yqd_JobPlan.Where(it => it.ItemID == SuperviseID && it.ItemType == 事项类型.专项交办).ToList();
            var progress = ctx.Yqd_PlanProgress.Where(it => it.ItemID == SuperviseID && it.ItemType == 事项类型.专项交办).ToList();
            var l = WxUser.LogonInfo;
            var DeptRole = l.Role.Any(it => it == 角色类型.管理员 || it == 角色类型.部门管理员);
            var MsRole = l.Role.Any(it => it == 角色类型.管理员 || it == 角色类型.督查人员 || it == 角色类型.督查管理员);
            object Assign = null;
            var IsLeadUnit = false;
            if (a != null)
            {
                List<string> listCooperativeUnit = new List<string>();
                if (!string.IsNullOrWhiteSpace(a.CooperativeUnit))
                {
                    listCooperativeUnit = JsonConvert.DeserializeObject<List<string>>(a.CooperativeUnit);
                }
                IsLeadUnit = a.LeadUnit == l.UnitCode;
                Assign = new
                {
                    a.AssignID,
                    Unit = dept.FirstOrDefault(it => it.UnitCode == a.UnitCode)?.Name,
                    UnitCode = a.LeadUnit,
                    LeadUnit = dept.FirstOrDefault(it => it.UnitCode == a.LeadUnit)?.Name,
                    CooperativeUnit = string.IsNullOrWhiteSpace(a.CooperativeUnit) ? "" : string.Join(",", dept.Where(it => listCooperativeUnit.Contains(it.UnitCode)).Select(it => it.Name)),
                    CompleteLimit = a.CompleteLimit.ToString("yyyy-MM-dd"),
                    ReportLimit = a.ReportLimit.ToString("yyyy-MM-dd"),
                    FeedbackLoop = a.FeedbackLoop == 进展反馈周期.自定义 ? a.Days + "天" : a.FeedbackLoop.ToString(),
                    FeedbackLoopId = (int)a.FeedbackLoop,
                    //FeedbackLoopDate = SuperviseService.GetFbLoopDate(a.FeedbackLoop, a.Instime, p.CompleteTime, a.Days),
                    ProgressInfo = a.ProgressInfo ?? "",
                    Material = !string.IsNullOrWhiteSpace(a.Material) ? JArray.Parse(a.Material) : new JArray(),
                    ReportTime = a.ReportTime?.ToString("yyyy-MM-dd") ?? "",
                    Instime = a.Instime.ToString("yyyy-MM-dd")
                };
            }
            var approval = ctx.Yqd_SchemeApproval.Where(it => it.ItemID == SuperviseID && it.ItemType == 事项类型.专项交办).OrderByDescending(x => x.ApprovalID).FirstOrDefault();
            object SchemeApproval = null;
            if (approval != null)
            {
                SchemeApproval = new
                {
                    Leader = approval.Leader ?? "",
                    Dept = approval.Dept ?? "",
                    DeptLeader = approval.DeptLeader ?? "",
                    Attachment = !string.IsNullOrWhiteSpace(approval.Attachment) ? JsonConvert.DeserializeObject(approval.Attachment) : new object()
                };
            }
            var user = ctx.Yqd_User.Select(it => new { it.EmployeeCode, it.Name }).ToList();
            var pg = progress.Where(it => it.CheckStatus != 审核状态.退回);
            var Standards = new JArray();
            if (supervise.Standards.HasValue())
            {
                Standards = JArray.Parse(supervise.Standards);
            }
            return this.ToJson(new
            {
                success = true,
                DeptRole,
                MsRole,
                IsLeadUnit,
                TaskName,
                TaskID,
                data,
                oFields,
                SuperviseID,
                SNo = supervise.SNo,
                Standards,
                supervise.IsFinish,
                supervise.IsDelay,
                supervise.IsArchive,
                Evaluate = supervise.Evaluate ?? "",
                Problem = supervise.Problem ?? "",
                ShowEdit = l.Role.Any(it => it == 角色类型.管理员 || it == 角色类型.督查人员),
                ShowPj = supervise.Status == 任务状态.已完成 && string.IsNullOrWhiteSpace(supervise.Evaluate) && MsRole,
                Photos = !string.IsNullOrWhiteSpace(supervise.Photos) ? JArray.Parse(supervise.Photos) : new JArray(),
                CheckUnit = dept.FirstOrDefault(it => it.UnitCode == supervise.UnitCode)?.Name,
                Checker = user.FirstOrDefault(m => m.EmployeeCode == supervise.EmployeeCode)?.Name,
                CheckInstime = supervise.Instime.ToString("yyyy-MM-dd"),
                Status = supervise.Status.ToString().Replace("推进", ""),
                Assign,
                PlanProgress = (a != null && a.FeedbackLoop == 进展反馈周期.报送进展情况) ? pg.Where(x => x.AssignID == a.AssignID).ToList() : new List<Yqd_PlanProgress>(),
                SchemeApproval,
                ShowSchemeHistory = scheme.Any(s => s.CheckStatus == 审核状态.退回),
                ShowScheme = DeptRole && Assign != null && (scheme.Count == 0 || scheme.Any(s => s.IsComplete)),
                Scheme = sm.OrderBy(it => it.Instime).Select(n => new
                {
                    n.SchemeID,
                    JobTarget = n.JobTarget.Replace("\r\n", "<br/>"),
                    JobType = n.JobType.ToString(),
                    IsCheck = n.CheckStatus == Enm.审核状态.待审,
                    Plan = plan.Where(m => m.SchemeID == n.SchemeID).OrderBy(it => it.CompleteTime).Select(s => new
                    {
                        s.PlanID,
                        Measure = s.Measure ?? "",
                        s.Instime,
                        CompleteTime = s.CompleteTime.ToString("yyyy-MM-dd"),
                        CooperativeUnit = string.IsNullOrWhiteSpace(s.CooperativeUnit) ? "" : string.Join(",", dept.Where(it => ("," + s.CooperativeUnit + ",").Contains("," + it.UnitCode + ",")).Select(it => it.Name)),
                        PlanStatus = s.PlanStatus.ToString(),
                        s.FlowIsOver,
                        s.TimeLine,
                        ShowHistory = progress.Any(b => b.PlanID == s.PlanID && b.CheckStatus == 审核状态.退回),
                        LoopDate = string.IsNullOrWhiteSpace(s.TimeLine) || s.PlanStatus == 工作计划状态.已完成 ? new List<object>() : s.TimeLine.Split(",").Where(ld => !pg.Any(b => b.PlanID == s.PlanID && b.FeedbackTime == DateTime.Parse(ld) && (b.ProgressStatus == 0 || b.ProgressStatus == 任务状态.已完成))).Select(d => new { Name = d, Value = d }).ToList<object>(), // || b.ProgressStatus == 任务状态.正常推进
                        Progress = pg.Where(b => b.PlanID == s.PlanID).Select(m => new
                        {
                            m.ProgressID,
                            IsCheck = m.AuditStatus == 0,
                            ProgressInfo = m.ProgressInfo + (m.ProgressStatus != 任务状态.退回 ? " (" + m.ProgressStatus.ToString().Replace("推进", "") + ")" : ""),
                            ProgressStatus = m.ProgressStatus.ToString().Replace("推进", ""),
                            ProofMaterial = !string.IsNullOrWhiteSpace(m.ProofMaterial) ? JArray.Parse(m.ProofMaterial) : new JArray(),
                            m.Problem,
                            m.Experience,
                            m.CompleteCount,
                            m.CompletingCount,
                            fbTime = m.FeedbackTime.ToString("yyyy-MM-dd"),
                            ExperienceMaterial = !string.IsNullOrWhiteSpace(m.ExperienceMaterial) ? JArray.Parse(m.ExperienceMaterial) : new JArray(),
                            Feedbacker = user.FirstOrDefault(u => u.EmployeeCode == m.EmployeeCode)?.Name,
                            FeedbackInstime = m.Instime.ToString("yyyy-MM-dd HH:mm:ss"),
                            m.Instime
                        })
                    })
                })
            });
        }

        [User]
        public ActionResult GetSumList()
        {
            var TaskID = Form.GetLong("TaskID");
            var sdate = Form.GetString("sdate");
            var edate = Form.GetString("edate");
            var page = Form.GetInt("page", 1);
            var pagesize = Form.GetInt("pagesize", 0);
            var IsDc = Form.GetBool("IsDc", true);//默认督查
            var listAssigns = ctx.Yqd_Assign.Where(x => x.ItemType == 事项类型.专项交办).AsQueryable();
            if (TaskID > 0)
            {
                listAssigns = listAssigns.Where(x => x.TaskID == TaskID);
            }
            if (!string.IsNullOrEmpty(sdate))
            {
                var date = Convert.ToDateTime(sdate);
                listAssigns = listAssigns.Where(x => x.Instime >= date);
            }

            if (!string.IsNullOrEmpty(edate))
            {
                var date = Convert.ToDateTime(edate).AddDays(1);
                listAssigns = listAssigns.Where(x => x.Instime < date);
            }

            var assigns = listAssigns.Select(it => new { it.AssignID, it.ItemID, it.LeadUnit, it.CompleteLimit, it.Instime }).ToList();
            var listScheme = ctx.Yqd_Scheme.Where(x => x.ItemType == 事项类型.专项交办).AsQueryable();
            if (TaskID > 0)
            {
                listScheme = listScheme.Where(x => x.TaskID == TaskID);
            }
            var scheme = listScheme.Select(it => new { it.SchemeID, it.ItemID, it.JobTarget, it.Instime }).ToList();
            var sIDs = assigns.Select(it => it.ItemID).ToArray();


            var listSupervise = ctx.Yqd_SpecialSupervise.Where(it => !it.IsDel && sIDs.Contains(it.SuperviseID)).AsQueryable();
            if (TaskID > 0)
            {
                listSupervise = listSupervise.Where(x => x.TaskID == TaskID);
            }
            if (IsDc)
            {
                listSupervise = listSupervise.Where(x => x.TaskType == 专项类型.专项督查);
            }
            else
            {
                listSupervise = listSupervise.Where(x => x.TaskType == 专项类型.专项交办);
            }
            var supervises = listSupervise.ToList();
            var dept = ctx.Yqd_Unit.Select(it => new { it.UnitCode, it.Name }).ToList();
            string FieldName = "", FieldID = "";
            var tmp = ctx.Yqd_SpecialTemplate.FirstOrDefault(it => it.TaskID == TaskID && it.IsDq);
            if (tmp != null && tmp.Fields.HasValue())
            {
                var arr = JArray.Parse(tmp.Fields);
                var o = arr.FirstOrDefault(it => it["IsShow"] != null && it["IsShow"].ToString().ToLower() == "true");
                if (o == null) o = arr[0];
                FieldName = o["Name"]?.ToString() ?? "";
                FieldID = o["FieldID"]?.ToString() ?? "";
            }
            var totalcount = supervises.Count();
            if (pagesize > 0)
            {
                supervises = supervises.Skip((page - 1) * pagesize).Take(pagesize).ToList();
            }
            var data = new List<dynamic>();
            foreach (var s in supervises)
            {
                var a = assigns.FirstOrDefault(it => it.ItemID == s.SuperviseID);
                var sm = scheme.Where(it => it.ItemID == s.SuperviseID).OrderBy(it => it.Instime);
                string AssignLimit = s.Instime.ToString("yyyy-MM-dd");
                var Problem = string.Join("<br/>", sm.Select(it => it.JobTarget));
                var LeadUnit = dept.FirstOrDefault(it => it.UnitCode == a.LeadUnit)?.Name;
                var TaskName = "";
                if (s.TemplateData.HasValue() && FieldID != "")
                {
                    TaskName = JObject.Parse(s.TemplateData)[FieldID]?.ToString() ?? "";
                }

                var specialTask = ctx.Yqd_SpecialTask.Where(x => x.IsDel == 0 && x.TaskID == s.TaskID).FirstOrDefault();
                if (specialTask != null && !string.IsNullOrWhiteSpace(specialTask.TaskCode))
                {
                    s.SNo = specialTask.TaskCode + s.SNo;
                }

                data.Add(new
                {
                    s.SuperviseID,
                    SNo = s.SNo,
                    TaskName,
                    Problem,
                    LeadUnit,
                    AssignLimit,
                    s.IsFinish,
                    s.IsDelay
                });
            }
            return this.ToJson(new
            {
                success = true,
                totalcount,
                FieldName,
                data = data.OrderBy(it => it.AssignLimit)
            });
        }

        /// <summary>
        /// 是否提醒督办
        /// </summary>
        /// <returns></returns>
        [User]
        public ActionResult DoFinish()
        {
            var SuperviseID = Form.GetInt("SuperviseId", 0);
            var supervise = ctx.Yqd_SpecialSupervise.Where(x => x.SuperviseID == SuperviseID).Single();
            if (supervise != null)
            {
                supervise.IsFinish = true;
                var r = ctx.SaveChanges();

                return this.ToJson(new
                {
                    success = true,
                    ret = r
                });
            }

            return this.ToJson(new
            {
                success = false,
                ret = 0
            });
        }

        /// <summary>
        /// 是否归档  
        /// </summary>
        /// <returns></returns>
        [User]
        public ActionResult DoArchive()
        {
            var SuperviseID = Form.GetInt("SuperviseId", 0);
            var supervise = ctx.Yqd_SpecialSupervise.Where(x => x.SuperviseID == SuperviseID).Single();
            if (supervise != null)
            {
                supervise.IsArchive = true;
                var r = ctx.SaveChanges();

                return this.ToJson(new
                {
                    success = true,
                    ret = r
                });
            }

            return this.ToJson(new
            {
                success = false,
                ret = 0
            });
        }
        /// <summary>
        /// 申请延期
        /// </summary>
        /// <returns></returns>
        [User]
        public ActionResult DoApplyDelay()
        {
            var SuperviseID = Form.GetInt("SuperviseId", 0);
            var supervise = ctx.Yqd_SpecialSupervise.Where(x => x.SuperviseID == SuperviseID).Single();
            if (supervise != null)
            {
                supervise.IsDelay = true;
                var r = ctx.SaveChanges();

                return this.ToJson(new
                {
                    success = true,
                    ret = r
                });
            }

            return this.ToJson(new
            {
                success = false,
                ret = 0
            });
        }
        /// <summary>
        /// 10：工作方案审核；20：进展反馈审核；30：办结报告审核
        /// </summary>
        /// <returns></returns>
        [User]
        public ActionResult GetSuperviseList()
        {
            var ConfigID = Form.GetLong("TaskID");
            var TaskID = Form.GetLong("TaskID");
            var Status = Form.GetInt("Status", 0);//左侧导航 工作方案  进展反馈 办结报告
            var State = Form.GetString("state"); //空:全部 0：待审核 2：正常推进 3：预警 4：滞后
            var TaskType = Form.GetInt("TaskType", 0);
            var IsDc = Form.GetBool("IsDc", true);
            var key = Form.GetString("key");
            var isAssign = Form.GetString("isAssign");
            var unitcode = Form.GetString("unitcode", "");
            var Leader = Form.GetString("Leader", "王健");
            var isFinish = Form.GetInt("isFinish", 0);
            var isDelay = Form.GetInt("isDelay", 0);
            var isArchive = Form.GetInt("isArchive", 0);

            var year = Form.GetInt("Year", 0);
            var page = Form.GetInt("page", 1);
            var pagesize = Form.GetInt("pagesize", int.MaxValue);
            if (pagesize == 0) pagesize = int.MaxValue;
            var unSql = "";
            var sql = "1=1 and IsDel=0 ";
            if (isFinish > 0)
            {
                sql += " and [IsFinish]=1 and [isDelay]=0";
            }
            else
            {
                sql += " and [IsFinish]=0";
            }
            if (isDelay > 0)
            {
                sql += " and [isDelay]=1";
            }

            if (isArchive > 0)
            {
                sql += " and [isArchive]=1";
            }
            //else
            //{
            //    sql += " and [isDelay]=0";
            //}
            if (TaskType > 0)
            {
                sql += " and [TaskType]=" + TaskType;
            }
            if (!string.IsNullOrEmpty(isAssign))
            {
                sql += $" and [SuperviseID] not in(select ItemID from Yqd_Assign where ItemType={(int)事项类型.专项交办}) and status !=5";
            }
            else
            {
                if (IsDc)
                {
                    sql += $" and [SuperviseID] in(select ItemID from Yqd_Assign where ItemType={(int)事项类型.专项交办}) ";
                }
            }
            if (TaskID > 0)
            {
                sql += $" and ([TaskID]={TaskID} or [TaskID] in (select TaskID from Yqd_SpecialTask where IsDel=0 and ConfigID={ConfigID}) )";
            }

            if (!string.IsNullOrWhiteSpace(unitcode))
            {
                sql += $" and [SuperviseID] in(select ItemID from Yqd_Assign where ItemType={(int)事项类型.专项交办} and ((','+LeadUnit+',') like '%," + unitcode + ",%' or LeadUnit='" + unitcode + "') )  ";
            }


            if (Leader != "王健")
            {
                sql += $@" and (
UnitCode in (
select OrganizationCode from Yqd_Unit where UnitCode in (Select substring(a.unit, b.number, charindex(',', a.unit + ',', b.number) - b.number) From Yqd_UnitLeader a inner join master.dbo.spt_values b on b.number between 1 and len(a.unit) Where a.Leader = '{Leader}' and a.unit != '' {(year > 0 ? " and a.year=" + year : "")}))
or
UnitCode in (
select UnitCode from Yqd_Unit where UnitCode in (Select substring(a.unit, b.number, charindex(',', a.unit + ',', b.number) - b.number) From Yqd_UnitLeader a inner join master.dbo.spt_values b on b.number between 1 and len(a.unit) Where a.Leader = '{Leader}' and a.unit != ''{(year > 0 ? " and a.year=" + year : "")}))
)";
            }

            var l = WxUser.LogonInfo;
            var un = "";
            //if (IsDc)
            //{
            //    un = ctx.Yqd_User.FirstOrDefault(it => it.EmployeeCode == l.EmployeeCode)?.OrganizationName;
            //    if (!un.Contains("督查科"))
            //    {
            //        sql += $" and [EmployeeCode]='{l.EmployeeCode}'";
            //    }


            //}
            if (year > 0)
            {
                sql += $" and year(Instime)={year}";
            }

            if (key.Trim() != "")
            {
                sql += $" and lower(ltrim(rtrim([TemplateData]))) like '%{ key.ToLower().Trim()}%'";
            }

            unSql = sql;

            switch (Status)
            {
                case 10:
                    if (!string.IsNullOrEmpty(State))
                    {
                        if (State == "0")
                        {
                            sql += " and ([SuperviseID] in(select ItemID from Yqd_Scheme where ItemType=" + (int)事项类型.专项交办 + " and [CheckStatus]=" + (int)审核状态.待审 + ")) and [Status] in (2,3,4)";
                        }
                        else
                        {
                            sql += " and ([SuperviseID] in(select ItemID from Yqd_Scheme where ItemType=" + (int)事项类型.专项交办 + " and [CheckStatus]=" + (int)审核状态.待审 + ")) and [Status]=" + State;
                        }
                    }
                    else
                    {
                        sql += " and ([SuperviseID] in(select ItemID from Yqd_Scheme where ItemType=" + (int)事项类型.专项交办 + " and [CheckStatus]=" + (int)审核状态.待审 + "))";
                    }
                    unSql += " and ([SuperviseID] in(select ItemID from Yqd_Scheme where ItemType=" + (int)事项类型.专项交办 + " and [CheckStatus]=" + (int)审核状态.待审 + "))";
                    break;
                case 20:
                    if (!string.IsNullOrEmpty(State))
                    {
                        if (State == "0")
                        {
                            sql += " and ([SuperviseID] in(select ItemID from Yqd_PlanProgress where ItemType=" + (int)事项类型.专项交办 + " and [CheckStatus]=" + (int)审核状态.待审 + " and AuditStatus=0)) and [Status] in (2,3,4)";
                        }
                        else
                        {
                            sql += " and ([SuperviseID] in(select ItemID from Yqd_PlanProgress where ItemType=" + (int)事项类型.专项交办 + " and [CheckStatus]=" + (int)审核状态.待审 + ")) and [Status]=" + State;
                        }
                    }
                    else
                    {
                        sql += " and ([SuperviseID] in(select ItemID from Yqd_PlanProgress where ItemType=" + (int)事项类型.专项交办 + " and [CheckStatus]=" + (int)审核状态.待审 + "))";
                    }

                    unSql += " and [SuperviseID] in(select ItemID from Yqd_PlanProgress where ItemType=" + (int)事项类型.专项交办 + " and [CheckStatus]=" + (int)审核状态.待审 + " and AuditStatus=0)";
                    break;
                case 30:
                    if (!string.IsNullOrEmpty(State))
                    {
                        if (State == "0")
                        {
                            sql += " and ([SuperviseID] in(select ItemID from Yqd_FinishReport where ItemType=" + (int)事项类型.专项交办 + " and [CheckStatus]=" + (int)审核状态.待审 + ")) and [Status] in (1,2,3,4)";
                        }
                        else
                        {
                            sql += " and ([SuperviseID] in(select ItemID from Yqd_FinishReport where ItemType=" + (int)事项类型.专项交办 + " and [CheckStatus]=" + (int)审核状态.待审 + ")) and [Status]=" + State;
                        }
                    }
                    else
                    {
                        sql += " and ([SuperviseID] in(select ItemID from Yqd_FinishReport where ItemType=" + (int)事项类型.专项交办 + " and [CheckStatus]=" + (int)审核状态.待审 + "))";
                    }

                    unSql += " and [SuperviseID] in(select ItemID from Yqd_FinishReport where ItemType=" + (int)事项类型.专项交办 + " and [CheckStatus]=" + (int)审核状态.待审 + ")";
                    break;
                case 0:
                case 50:
                    if (!string.IsNullOrEmpty(State))
                    {
                        sql += $" and [Status]={State}  and IsArchive=0 ";
                    }
                    break;
            }

            int waitTotalcount = ctx.Database.SqlQuery<int>("select count(*) from Yqd_SpecialSupervise where " + unSql).First();
            //var(waitTotalcount, rs11) = ctx.Database.SqlPager<Yqd_SpecialSupervise>((page - 1) * pagesize, pagesize, "*", unSql, "[SuperviseID] desc");
            var taskIDs = ctx.Yqd_SpecialTask.Where(it => it.IsDel == 0 && TaskID == 0 ? it.TaskID > 0 : it.ConfigID == ConfigID).Select(it => (long)it.TaskID).ToArray();
            var assigns = ctx.Yqd_Assign.Where(it => (it.TaskID == TaskID || taskIDs.Contains(it.TaskID)) && it.ItemType == 事项类型.专项交办).Select(it => new { it.AssignID, it.ItemID, it.LeadUnit, it.CompleteLimit, it.Instime, it.TaskID }).ToList();
            var schemes = ctx.Yqd_Scheme.Where(it => (it.TaskID == TaskID || taskIDs.Contains(it.TaskID)) && it.ItemType == 事项类型.专项交办 && it.CheckStatus != 审核状态.退回).Select(it => new { it.SchemeID, it.ItemID, it.JobTarget, it.Instime }).ToList();
            var dept = ctx.Yqd_Unit.Select(it => new { it.UnitCode, it.Name, it.OrganizationCode }).ToList();
            string FieldName = "", FieldID = "", fID = "";
            // var tmp = ctx.Yqd_SpecialTemplate.Where(it => (it.TaskID == TaskID || taskIDs.Contains(it.TaskID)) && it.IsDq).ToList();
            //var tmp = ctx.Yqd_SpecialTemplate.Where(it => (it.TaskID == TaskID || taskIDs.Contains(it.TaskID))).ToList();
            var tmp = ctx.Yqd_SpecialTemplate.Where(it => (TaskID == 0 ? it.TaskID > 0 : (it.TaskID == TaskID || taskIDs.Contains(it.TaskID)))).ToList();


            var listUnit = assigns.GroupBy(x => x.LeadUnit).Select(x => x.Key.ToString()).ToList();

            var (totalcount, rs) = ctx.Database.SqlPager<Yqd_SpecialSupervise>((page - 1) * pagesize, pagesize, "*,(select TOP 1 Instime from Yqd_Assign where taskId=Yqd_SpecialSupervise.taskId and ItemID=SuperviseID ORDER BY Instime DESC) AssignTime,(select top 1 Instime from [Yqd_PlanProgress] where taskId=Yqd_SpecialSupervise.taskId and ItemID=SuperviseID ORDER BY Instime DESC) as ProgressTime", sql, "ProgressTime desc , [AssignTime] desc");
            var data = new List<dynamic>();

            var listSupervise = ctx.Database.SqlQuery<Yqd_SpecialSupervise>("select * From Yqd_SpecialSupervise where " + sql).Select(x => x.SuperviseID).ToList();
            string sql2 = "";
            List<string> listAssign = new List<string>();
            if (listSupervise.Any())
            {
                sql2 = "and itemid in (" + string.Join(",", listSupervise) + ")";
                listAssign = ctx.Database.SqlQuery<Yqd_Assign>("select * From Yqd_Assign where ItemType=40 " + sql2).GroupBy(x => x.LeadUnit).Select(x => x.Key.ToString()).ToList();
            }

            foreach (var s in rs)
            {
                string AssignLimit = "", lUnit = "", AssignTime = "";
                var a = assigns.Where(x => x.ItemID == s.SuperviseID).OrderByDescending(x => x.Instime).FirstOrDefault();
                if (a != null)
                {
                    AssignLimit = a.CompleteLimit.ToString("yyyy-MM-dd");
                    lUnit = a.LeadUnit;
                    AssignTime = a.Instime.ToString("yyyy-MM-dd");
                }
                var sm = schemes.Where(it => it.ItemID == s.SuperviseID).OrderBy(it => it.Instime);
                var Problem = string.Join("<br/>", sm.Select(it => it.JobTarget));
                var LeadUnit = dept.FirstOrDefault(it => it.UnitCode == lUnit || it.OrganizationCode == lUnit)?.Name;
                var LeadUnitCode = lUnit;
                var TaskName = "";


                var tp = tmp.FirstOrDefault(it => it.TemplateID == s.TemplateID);
                if (tp != null && tp.Fields.HasValue())
                {

                    var arr = JArray.Parse(tp.Fields);
                    var o = arr.FirstOrDefault(it => it["IsShow"] != null && it["IsShow"].ToString().ToLower() == "true");
                    if (o == null) o = arr[0];
                    FieldName = o["Name"]?.ToString() ?? "";
                    FieldID = o["FieldID"]?.ToString() ?? "";

                    //o = arr.FirstOrDefault(it => it["Name"] != null && it["Name"].ToString().Trim() == "镇街");
                    //if (o == null) o = arr[0];
                    //fID = o["FieldID"]?.ToString() ?? "";
                    fID = FieldID;
                }
                if (s.TemplateData.HasValue() && FieldID != "")
                {
                    var d = JObject.Parse(s.TemplateData);
                    if (IsDc)
                    {
                        TaskName = d[fID]?.ToString() ?? "";
                    }
                    else
                    {
                        TaskName = d[FieldID]?.ToString() ?? "";
                    }
                }
                //(s.TaskType == 专项类型.专项交办 ? "JB" : "DC") + s.SNo
                var specialTask = ctx.Yqd_SpecialTask.Where(x => x.IsDel == 0 && x.TaskID == s.TaskID).FirstOrDefault();
                if (specialTask != null && !string.IsNullOrWhiteSpace(specialTask.TaskCode))
                {
                    s.SNo = specialTask.TaskCode + s.SNo;
                }

                var progress = ctx.Yqd_PlanProgress.Where(x => x.ItemID == s.SuperviseID && x.TaskID == s.TaskID).OrderByDescending(x => x.Instime).FirstOrDefault();
                string progressTime = progress != null ? progress.Instime.ToString("yyyy-MM-dd") : "";
                data.Add(new
                {
                    s.TaskID,
                    s.SuperviseID,
                    SNo = s.SNo,
                    Status = s.Status.ToString(),
                    TaskName,
                    Problem,
                    LeadUnit,
                    LeadUnitCode,
                    AssignTime,
                    AssignLimit,
                    progressTime,
                    s.IsFinish,
                    s.IsDelay
                });
            }
            var totalPages = totalcount != 0 ? (totalcount % pagesize) == 0 ? (totalcount / pagesize) : (totalcount / pagesize) + 1 : 0;

            return this.ToJson(new
            {
                success = true,
                totalcount,
                totalPages,
                waitTotalcount = waitTotalcount,
                FieldName,
                data,
                sql,
                unitList = listAssign.Any() ? ctx.Yqd_Unit.Where(it => listAssign.Contains(it.UnitCode)).ToList() : new List<Yqd_Unit>(),
            });
        }

        public ActionResult GetSuperviseListByPage()
        {
            var ConfigID = Form.GetLong("TaskID");
            var TaskID = Form.GetLong("TaskID", 49);
            var Status = Form.GetInt("Status", 0);//左侧导航 工作方案  进展反馈 办结报告
            var State = Form.GetString("state"); //空:全部 0：待审核 2：正常推进 3：预警 4：滞后
            var TaskType = Form.GetInt("TaskType", 1);
            var IsDc = Form.GetBool("IsDc", true);
            var key = Form.GetString("key");
            var isAssign = Form.GetString("isAssign");
            var unitcode = Form.GetString("unitcode", "");

            var year = Form.GetInt("Year", 2023);
            var page = Form.GetInt("page", 0);
            var pagesize = Form.GetInt("pagesize", int.MaxValue);
            if (pagesize == 0) pagesize = int.MaxValue;
            var unSql = "";
            var sql = "1=1 and IsDel=0 ";
            if (TaskType > 0)
            {
                sql += " and [TaskType]=" + TaskType;
            }
            if (!string.IsNullOrEmpty(isAssign))
            {
                sql += $" and [SuperviseID] not in(select ItemID from Yqd_Assign where ItemType={(int)事项类型.专项交办}) and status !=5";
            }
            else
            {
                if (IsDc)
                {
                    sql += $" and [SuperviseID] in(select ItemID from Yqd_Assign where ItemType={(int)事项类型.专项交办}) ";
                }
            }
            if (TaskID > 0)
            {
                sql += $" and ([TaskID]={TaskID} or [TaskID] in (select TaskID from Yqd_SpecialTask where IsDel=0 and ConfigID={ConfigID}) )";
            }

            if (!string.IsNullOrWhiteSpace(unitcode))
            {
                sql += $" and [SuperviseID] in(select ItemID from Yqd_Assign where ItemType={(int)事项类型.专项交办} and ((','+LeadUnit+',') like '%," + unitcode + ",%' or LeadUnit='" + unitcode + "') )  ";
            }

            var l = WxUser.LogonInfo;
            var un = "";
            //if (IsDc)
            //{
            //    un = ctx.Yqd_User.FirstOrDefault(it => it.EmployeeCode == l.EmployeeCode)?.OrganizationName;
            //    if (!un.Contains("督查科"))
            //    {
            //        sql += $" and [EmployeeCode]='{l.EmployeeCode}'";
            //    }


            //}
            if (year > 0)
            {
                sql += $" and year(Instime)={year}";
            }

            if (key.Trim() != "")
            {
                sql += $" and lower(ltrim(rtrim([TemplateData]))) like '%{ key.ToLower().Trim()}%'";
            }

            unSql = sql;

            switch (Status)
            {
                case 10:
                    if (!string.IsNullOrEmpty(State))
                    {
                        if (State == "0")
                        {
                            sql += " and ([SuperviseID] in(select ItemID from Yqd_Scheme where ItemType=" + (int)事项类型.专项交办 + " and [CheckStatus]=" + (int)审核状态.待审 + ")) and [Status] in (2,3,4)";
                        }
                        else
                        {
                            sql += " and ([SuperviseID] in(select ItemID from Yqd_Scheme where ItemType=" + (int)事项类型.专项交办 + " and [CheckStatus]=" + (int)审核状态.待审 + ")) and [Status]=" + State;
                        }
                    }
                    else
                    {
                        sql += " and ([SuperviseID] in(select ItemID from Yqd_Scheme where ItemType=" + (int)事项类型.专项交办 + " and [CheckStatus]=" + (int)审核状态.待审 + "))";
                    }
                    unSql += " and ([SuperviseID] in(select ItemID from Yqd_Scheme where ItemType=" + (int)事项类型.专项交办 + " and [CheckStatus]=" + (int)审核状态.待审 + "))";
                    break;
                case 20:
                    if (!string.IsNullOrEmpty(State))
                    {
                        if (State == "0")
                        {
                            sql += " and ([SuperviseID] in(select ItemID from Yqd_PlanProgress where ItemType=" + (int)事项类型.专项交办 + " and [CheckStatus]=" + (int)审核状态.待审 + " and AuditStatus=0)) and [Status] in (2,3,4)";
                        }
                        else
                        {
                            sql += " and ([SuperviseID] in(select ItemID from Yqd_PlanProgress where ItemType=" + (int)事项类型.专项交办 + " and [CheckStatus]=" + (int)审核状态.待审 + ")) and [Status]=" + State;
                        }
                    }
                    else
                    {
                        sql += " and ([SuperviseID] in(select ItemID from Yqd_PlanProgress where ItemType=" + (int)事项类型.专项交办 + " and [CheckStatus]=" + (int)审核状态.待审 + "))";
                    }

                    unSql += " and [SuperviseID] in(select ItemID from Yqd_PlanProgress where ItemType=" + (int)事项类型.专项交办 + " and [CheckStatus]=" + (int)审核状态.待审 + " and AuditStatus=0)";
                    break;
                case 30:
                    if (!string.IsNullOrEmpty(State))
                    {
                        if (State == "0")
                        {
                            sql += " and ([SuperviseID] in(select ItemID from Yqd_FinishReport where ItemType=" + (int)事项类型.专项交办 + " and [CheckStatus]=" + (int)审核状态.待审 + ")) and [Status] in (1,2,3,4)";
                        }
                        else
                        {
                            sql += " and ([SuperviseID] in(select ItemID from Yqd_FinishReport where ItemType=" + (int)事项类型.专项交办 + " and [CheckStatus]=" + (int)审核状态.待审 + ")) and [Status]=" + State;
                        }
                    }
                    else
                    {
                        sql += " and ([SuperviseID] in(select ItemID from Yqd_FinishReport where ItemType=" + (int)事项类型.专项交办 + " and [CheckStatus]=" + (int)审核状态.待审 + "))";
                    }

                    unSql += " and [SuperviseID] in(select ItemID from Yqd_FinishReport where ItemType=" + (int)事项类型.专项交办 + " and [CheckStatus]=" + (int)审核状态.待审 + ")";
                    break;
                case 0:
                case 50:
                    if (!string.IsNullOrEmpty(State))
                    {
                        sql += $" and [Status]={State}";
                    }
                    break;
            }


            //var(waitTotalcount, rs11) = ctx.Database.SqlPager<Yqd_SpecialSupervise>((page - 1) * pagesize, pagesize, "*", unSql, "[SuperviseID] desc");
            var taskIDs = ctx.Yqd_SpecialTask.Where(it => it.IsDel == 0 && TaskID == 0 ? it.TaskID > 0 : it.ConfigID == ConfigID).Select(it => (long)it.TaskID).ToArray();
            var assigns = ctx.Yqd_Assign.Where(it => (it.TaskID == TaskID || taskIDs.Contains(it.TaskID)) && it.ItemType == 事项类型.专项交办).Select(it => new { it.AssignID, it.ItemID, it.LeadUnit, it.CompleteLimit, it.Instime, it.TaskID, it.CooperativeUnit }).ToList();
            var dept = ctx.Yqd_Unit.Select(it => new { it.UnitCode, it.Name, it.OrganizationCode }).ToList();
            string FieldName = "", FieldID = "", fID = "";
            // var tmp = ctx.Yqd_SpecialTemplate.Where(it => (it.TaskID == TaskID || taskIDs.Contains(it.TaskID)) && it.IsDq).ToList();
            //var tmp = ctx.Yqd_SpecialTemplate.Where(it => (it.TaskID == TaskID || taskIDs.Contains(it.TaskID))).ToList();
            var tmp = ctx.Yqd_SpecialTemplate.Where(it => (TaskID == 0 ? it.TaskID > 0 : (it.TaskID == TaskID || taskIDs.Contains(it.TaskID)))).ToList();
            var rs = new List<Yqd_SpecialSupervise>();
            int totalcount = 0;
            if (page == 0)
            {
                //查询全部
                rs = ctx.Database.SqlQuery<Yqd_SpecialSupervise>("select *,(select TOP 1 Instime from Yqd_Assign where taskId=Yqd_SpecialSupervise.taskId and ItemID=SuperviseID ORDER BY Instime DESC) AssignTime from Yqd_SpecialSupervise where " + sql + " order by [AssignTime] desc");
                totalcount = rs.Count;
            }
            else
            {
                //分页
                var (totalcount1, rs1) = ctx.Database.SqlPager<Yqd_SpecialSupervise>((page - 1) * pagesize, pagesize, "*,(select TOP 1 Instime from Yqd_Assign where taskId=Yqd_SpecialSupervise.taskId and ItemID=SuperviseID ORDER BY Instime DESC) AssignTime", sql, "[AssignTime] desc");
                rs = rs1;
                totalcount = totalcount1;
            }
            var data = new List<dynamic>();


            foreach (var s in rs)
            {
                List<string> listCooperativeUnit = new List<string>();
                string AssignLimit = "", lUnit = "", AssignTime = "";
                var a = assigns.Where(x => x.ItemID == s.SuperviseID).OrderByDescending(x => x.Instime).FirstOrDefault();
                if (a != null)
                {
                    AssignLimit = a.CompleteLimit.ToString("yyyy-MM-dd");//完成时间
                    lUnit = a.LeadUnit;
                    AssignTime = a.Instime.ToString("yyyy-MM-dd");//交办时间
                    if (!string.IsNullOrWhiteSpace(a.CooperativeUnit))
                    {
                        listCooperativeUnit = JsonConvert.DeserializeObject<List<string>>(a.CooperativeUnit);
                    }
                }
                var LeadUnit = dept.FirstOrDefault(it => it.UnitCode == lUnit || it.OrganizationCode == lUnit)?.Name;//主办单位
                var CooperativeUnit = string.IsNullOrWhiteSpace(a.CooperativeUnit) ? "" : string.Join(",", dept.Where(it => listCooperativeUnit.Contains(it.UnitCode)).Select(it => it.Name));//协办单位

                var LeadUnitCode = lUnit;
                var TaskName = "";
                var f = tmp.FirstOrDefault(it => it.TemplateID == s.TemplateID);
                //if (tp != null && tp.Fields.HasValue())
                //{

                //    var arr = JArray.Parse(tp.Fields);
                //    var o = arr.FirstOrDefault(it => it["IsShow"] != null && it["IsShow"].ToString().ToLower() == "true");
                //    if (o == null) o = arr[0];
                //    FieldName = o["Name"]?.ToString() ?? "";
                //    FieldID = o["FieldID"]?.ToString() ?? "";

                //    //o = arr.FirstOrDefault(it => it["Name"] != null && it["Name"].ToString().Trim() == "镇街");
                //    //if (o == null) o = arr[0];
                //    //fID = o["FieldID"]?.ToString() ?? "";
                //    fID = FieldID;
                //}
                var Fields = new JArray();
                var oFields = new JObject();
                if (f != null)
                {
                    if (f.Fields.HasValue()) Fields = JArray.Parse(f.Fields);
                    if (f.oFields.HasValue()) oFields = JObject.Parse(f.oFields);
                }
                JObject Targets = null;
                if (s.TemplateData.HasValue())
                {
                    Targets = JObject.Parse(s.TemplateData);
                }
                var taskRequirement = "";//任务要求
                if (Targets != null)
                {
                    foreach (var o in Fields)
                    {
                        var k = o["FieldID"].ToString();
                        var text = o["Name"]?.ToString() ?? "";
                        if (text == "任务名称")
                        {
                            TaskName = Targets[k]?.ToString() ?? "";
                        }
                        else if (text == "任务要求")
                        {
                            taskRequirement = Targets[k]?.ToString() ?? "";
                        }
                        //data.Add(new
                        //{
                        //    text = o["Name"]?.ToString() ?? "",
                        //    value = Targets[key]?.ToString() ?? ""
                        //});
                    }
                }

                //if (s.TemplateData.HasValue() && FieldID != "")
                //{
                //    var d = JObject.Parse(s.TemplateData);
                //    if (IsDc)
                //    {
                //        TaskName = d[fID]?.ToString() ?? "";
                //    }
                //    else
                //    {
                //        TaskName = d[FieldID]?.ToString() ?? "";
                //    }
                //}

                data.Add(new
                {
                    s.TaskID,
                    s.SuperviseID,
                    s.IsFinish,
                    s.IsDelay,
                    Status = s.Status.ToString(),//状态
                    TaskName,//任务名称
                    LeadUnit,//主办单位
                    CooperativeUnit,//协办单位
                    AssignTime,//交办时间
                    CompleteTime = AssignLimit,//完成时间
                    TaskRequirement = taskRequirement //任务要求
                });
            }
            var totalPages = page == 0 ? 0 : totalcount != 0 ? (totalcount % pagesize) == 0 ? (totalcount / pagesize) : (totalcount / pagesize) + 1 : 0;

            return this.ToJson(new
            {
                success = true,
                totalcount,
                totalPages,
                data
            });
        }

        public ActionResult GetSuperviseDetails()
        {
            var SuperviseID = Form.GetInt("SuperviseID");
            var supervise = ctx.Yqd_SpecialSupervise.FirstOrDefault(it => it.SuperviseID == SuperviseID);
            if (supervise == null)
            {
                return this.ToJson(new
                {
                    success = true,
                    data = new List<object>()
                });
            }
            var TaskName = "";
            string taskRequirement = "";
            var TaskID = 0;
            JObject Targets = null;
            var task = ctx.Yqd_SpecialTask.FirstOrDefault(it => it.TaskID == supervise.TaskID);
            if (task != null)
            {
                TaskID = task.TaskID;
                //TaskName = task.Name;
                //supervise.SNo = task.TaskCode + supervise.SNo;
            }
            var f = ctx.Yqd_SpecialTemplate.FirstOrDefault(it => it.TemplateID == supervise.TemplateID);
            var Fields = new JArray();
            var oFields = new JObject();
            if (f != null)
            {
                if (f.Fields.HasValue()) Fields = JArray.Parse(f.Fields);
                if (f.oFields.HasValue()) oFields = JObject.Parse(f.oFields);
            }
            if (supervise.TemplateData.HasValue())
            {
                Targets = JObject.Parse(supervise.TemplateData);
            }
            var data = new List<object>();
            if (Targets != null)
            {
                foreach (var o in Fields)
                {
                    var k = o["FieldID"].ToString();
                    var text = o["Name"]?.ToString() ?? "";
                    if (text == "任务名称")
                    {
                        TaskName = Targets[k]?.ToString() ?? "";
                    }
                    else if (text == "任务要求")
                    {
                        taskRequirement = Targets[k]?.ToString() ?? "";
                    }
                }

                //foreach (var o in Fields)
                //{
                //    var key = o["FieldID"].ToString();
                //    data.Add(new
                //    {
                //        text = o["Name"]?.ToString() ?? "",
                //        value = Targets[key]?.ToString() ?? ""
                //    });
                //}
            }
            var dept = ctx.Yqd_Unit.Select(it => new { it.UnitCode, it.Name }).ToList();
            var a = ctx.Yqd_Assign.FirstOrDefault(it => it.ItemID == SuperviseID && it.ItemType == 事项类型.专项交办);
            dynamic Assign = null;
            if (a != null)
            {
                List<string> listCooperativeUnit = new List<string>();
                if (!string.IsNullOrWhiteSpace(a.CooperativeUnit))
                {
                    listCooperativeUnit = JsonConvert.DeserializeObject<List<string>>(a.CooperativeUnit);
                }
                Assign = new
                {
                    a.AssignID,
                    Unit = dept.FirstOrDefault(it => it.UnitCode == a.UnitCode)?.Name,
                    UnitCode = a.LeadUnit,
                    LeadUnit = dept.FirstOrDefault(it => it.UnitCode == a.LeadUnit)?.Name,
                    CooperativeUnit = string.IsNullOrWhiteSpace(a.CooperativeUnit) ? "" : string.Join(",", dept.Where(it => listCooperativeUnit.Contains(it.UnitCode)).Select(it => it.Name)),
                    CompleteLimit = a.CompleteLimit.ToString("yyyy-MM-dd"),
                    ReportLimit = a.ReportLimit.ToString("yyyy-MM-dd"),
                    FeedbackLoop = a.FeedbackLoop == 进展反馈周期.自定义 ? a.Days + "天" : a.FeedbackLoop.ToString(),
                    FeedbackLoopId = (int)a.FeedbackLoop,
                    //FeedbackLoopDate = SuperviseService.GetFbLoopDate(a.FeedbackLoop, a.Instime, p.CompleteTime, a.Days),
                    ReportTime = a.ReportTime?.ToString("yyyy-MM-dd") ?? "",
                    Instime = a.Instime.ToString("yyyy-MM-dd")
                };
            }
            return this.ToJson(new
            {
                success = true,
                TaskID,
                SuperviseID,
                supervise.IsFinish,
                supervise.IsDelay,
                TaskName,//任务名称
                Assign.LeadUnit,//主办单位
                Assign.CooperativeUnit,//协办单位
                AssignTime = Assign.Instime,//交办时间
                CompleteTime = Assign.CompleteLimit,//完成时间
                TaskRequirement = taskRequirement //任务要求
            });
        }

        [User]
        public ActionResult GetAssignList()
        {
            var ConfigID = Form.GetLong("TaskID");
            var TaskID = Form.GetInt("TaskID");
            var year = Form.GetInt("Year", 0);
            var page = Form.GetInt("page", 1);
            var pagesize = Form.GetInt("pagesize", int.MaxValue);
            var sql = "1=1 and IsDel=0 ";
            if (TaskID > 0)
            {
                sql += $"and ([TaskID]={TaskID} or [TaskID] in (select TaskID from Yqd_SpecialTask where IsDel=0 and ConfigID={ConfigID}))";
            }
            sql += $" and [SuperviseID] not in(select ItemID from Yqd_Assign where ItemType={(int)事项类型.专项交办}) and status !=5";
            if (year > 0) sql += $" and year([Instime])={year}";
            var (totalcount, rs) = ctx.Database.SqlPager<Yqd_SpecialSupervise>((page - 1) * pagesize, pagesize, "*", sql, "[Instime] desc");
            var data = new List<object>();
            string TaskName = "";
            if (TaskID > 0)
            {
                var task = ctx.Yqd_SpecialTask.FirstOrDefault(it => it.TaskID == TaskID);
                if (task != null) TaskName = task.Name;
            }
            var template = ctx.Yqd_SpecialTemplate.Select(it => new { it.TemplateID, it.Fields, it.oFields }).ToList();
            var standard = ctx.Yqd_SpecialStandard.Where(it => it.TaskID == TaskID).Select(it => new { it.StandardID, it.Content }).ToList();
            var dept = ctx.Yqd_Unit.Select(it => new { it.UnitCode, it.Name }).ToList();
            var user = ctx.Yqd_User.Select(it => new { it.EmployeeCode, it.Name }).ToList();
            string FieldName = "", FieldID = "", fID = "";
            foreach (var d in rs)
            {
                var tp = template.FirstOrDefault(it => it.TemplateID == d.TemplateID);
                var Fields = new JArray();
                var oFields = new JObject();
                if (tp != null)
                {
                    if (tp.Fields.HasValue()) Fields = JArray.Parse(tp.Fields);
                    if (tp.oFields.HasValue()) oFields = JObject.Parse(tp.oFields);

                    var arr = JArray.Parse(tp.Fields);

                    var o = arr.FirstOrDefault(it => it["IsShow"] != null && it["IsShow"].ToString().ToLower() == "true");
                    if (o == null) o = arr[0];
                    FieldName = o["Name"]?.ToString() ?? "";
                    //FieldID = o["FieldID"]?.ToString() ?? "";
                    //o = arr.FirstOrDefault(it => it["Name"] != null && it["Name"].ToString().Trim() == "镇街");
                    //if (o == null) o = arr[0];
                    //fID = o["FieldID"]?.ToString() ?? "";

                }
                JObject Targets = null;
                if (d.TemplateData.HasValue())
                {
                    Targets = JObject.Parse(d.TemplateData);
                }
                var ts = new List<object>();
                if (Targets != null)
                {
                    foreach (var o in Fields)
                    {
                        var key = o["FieldID"].ToString();
                        ts.Add(new
                        {
                            text = o["Name"]?.ToString() ?? "",
                            value = Targets[key]?.ToString() ?? ""
                        });
                    }
                }
                var Standards = new JArray();
                if (d.Standards.HasValue())
                {
                    Standards = JArray.Parse(d.Standards);
                }
                if (TaskID == 0)
                {
                    var task = ctx.Yqd_SpecialTask.FirstOrDefault(it => it.TaskID == d.TaskID);
                    if (task != null) TaskName = task.Name;
                }
                var specialTask = ctx.Yqd_SpecialTask.Where(x => x.IsDel == 0 && x.TaskID == d.TaskID).FirstOrDefault();
                if (specialTask != null && !string.IsNullOrWhiteSpace(specialTask.TaskCode))
                {
                    d.SNo = specialTask.TaskCode + d.SNo;
                }
                data.Add(new
                {
                    d.SuperviseID,
                    d.TaskID,
                    TaskName,
                    oFields,
                    Targets = ts,
                    Standards,
                    d.Problem,
                    Photos = string.IsNullOrWhiteSpace(d.Photos) ? new JArray() : JArray.Parse(d.Photos),
                    CheckUnit = dept.FirstOrDefault(it => it.UnitCode == d.UnitCode)?.Name,
                    Checker = user.FirstOrDefault(m => m.EmployeeCode == d.EmployeeCode)?.Name,
                    CheckInstime = d.Instime.ToString("yyyy-MM-dd"),
                    SNo = d.SNo,
                    Status = d.Status.ToString(),
                    d.IsFinish,
                    d.IsDelay
                });
            }
            return this.ToJson(new
            {
                success = true,
                totalcount,
                data,
                FieldName,
            });
        }



        [User]
        public ActionResult Get()
        {
            var SuperviseID = Form.GetInt("SuperviseID");
            var supervise = ctx.Yqd_SpecialSupervise.FirstOrDefault(it => it.SuperviseID == SuperviseID);
            if (supervise == null)
            {
                return this.ToJson(new
                {
                    success = true
                });
            }
            string TaskName = "";
            var task = ctx.Yqd_SpecialTask.FirstOrDefault(it => it.TaskID == supervise.TaskID);
            if (task != null) TaskName = task.Name;
            var template = ctx.Yqd_SpecialTemplate.FirstOrDefault(it => it.TemplateID == supervise.TemplateID);
            var Fields = new JArray();
            var oFields = new JObject();
            if (template != null)
            {
                if (template.Fields.HasValue()) Fields = JArray.Parse(template.Fields);
                if (template.oFields.HasValue()) oFields = JObject.Parse(template.oFields);
            }
            JObject Targets = null;
            if (supervise.TemplateData.HasValue())
            {
                Targets = JObject.Parse(supervise.TemplateData);
            }
            var data = new List<object>();
            if (Targets != null)
            {
                foreach (var o in Fields)
                {
                    var key = o["FieldID"].ToString();
                    var fvalue = new JArray();
                    var val = o["FieldValue"]?.ToString() ?? "";
                    if (val.HasValue()) fvalue = JArray.Parse(val);
                    data.Add(new
                    {
                        text = o["Name"]?.ToString() ?? "",
                        ftype = o["FieldType"]?.ToString() ?? "",
                        fvalue,
                        value = Targets[key]?.ToString() ?? ""
                    });
                }
            }
            var r = ctx.Database.SqlQuery<Yqd_SpecialStandard>("select * from Yqd_SpecialStandard where TaskID={0} order by Tactic asc", supervise.TaskID);
            return this.ToJson(new
            {
                success = true,
                TaskName,
                data,
                Fields,
                oFields,
                sd = r.Select(it => new
                {
                    it.StandardID,
                    it.Content
                }),
                Standards = string.IsNullOrWhiteSpace(supervise.Standards) ? new JArray() : JArray.Parse(supervise.Standards),
                supervise.Problem,
                Photos = string.IsNullOrWhiteSpace(supervise.Photos) ? new JArray() : JArray.Parse(supervise.Photos),
                supervise.IsFinish,
                supervise.IsDelay
            });
        }



        [User]
        public ActionResult GetSupervise()
        {
            var SuperviseID = Form.GetInt("SuperviseID");
            var supervise = ctx.Yqd_SpecialSupervise.FirstOrDefault(it => it.SuperviseID == SuperviseID);
            if (supervise == null)
            {
                return this.ToJson(new
                {
                    success = true
                });
            }
            var data = new List<object>();
            string TaskName = "";
            var task = ctx.Yqd_SpecialTask.FirstOrDefault(it => it.TaskID == supervise.TaskID);
            if (task != null) TaskName = task.Name;
            var tp = ctx.Yqd_SpecialTemplate.FirstOrDefault(it => it.TemplateID == supervise.TemplateID);
            var Fields = new JArray();
            var oFields = new JObject();
            if (tp != null)
            {
                if (tp.Fields.HasValue()) Fields = JArray.Parse(tp.Fields);
                if (tp.oFields.HasValue()) oFields = JObject.Parse(tp.oFields);
            }
            JObject Targets = null;
            if (supervise.TemplateData.HasValue())
            {
                Targets = JObject.Parse(supervise.TemplateData);
            }
            var ts = new List<object>();
            if (Targets != null)
            {
                foreach (var o in Fields)
                {
                    var key = o["FieldID"].ToString();
                    ts.Add(new
                    {
                        text = o["Name"]?.ToString() ?? "",
                        value = Targets[key]?.ToString() ?? ""
                    });
                }
            }
            var Standards = new JArray();
            if (supervise.Standards.HasValue())
            {
                Standards = JArray.Parse(supervise.Standards);
            }
            var CheckUnit = ctx.Yqd_Unit.FirstOrDefault(it => it.UnitCode == supervise.UnitCode)?.Name;
            var Checker = ctx.Yqd_User.FirstOrDefault(m => m.EmployeeCode == supervise.EmployeeCode)?.Name;
            return this.ToJson(new
            {
                success = true,
                SuperviseID,
                supervise.TaskID,
                TaskName,
                oFields,
                Targets = ts,
                Standards,
                supervise.Problem,
                Photos = string.IsNullOrWhiteSpace(supervise.Photos) ? new JArray() : JArray.Parse(supervise.Photos),
                Checker,
                CheckUnit,
                CheckInstime = supervise.Instime.ToString("yyyy-MM-dd"),
                AssignLimit = supervise.Instime.AddDays(7).ToString("yyyy-MM-dd"),
                supervise.IsFinish,
                supervise.IsDelay
            });
        }

        /// <summary>
        /// 添加专项督查
        /// </summary>
        /// datas:{LeadUnit:"",CooperativeUnit:"",ReportLimit:"",CompleteLimit:"",FeedbackLoop:""}
        /// <returns></returns>
        [User]
        public IActionResult Add(Yqd_SpecialSupervise model)
        {
            var data = Form.GetString("datas");
            model.SNo = GetSuperviseNo(model.TaskID, model.TaskType);
            model.Instime = DateTime.Now;
            model.Status = 任务状态.正常推进;
            model.EmployeeCode = WxUser.LogonInfo.EmployeeCode;
            model.UnitCode = WxUser.LogonInfo.UnitCode;
            ctx.Yqd_SpecialSupervise.Add(model);
            var ret = ctx.SaveChanges();
            if (ret > 0)
            {
                if (data.HasValue())
                {
                    var o = JObject.Parse(data);
                    var loop = int.Parse(o["FeedbackLoop"].ToString());
                    var m = new Yqd_Assign
                    {
                        TaskID = model.TaskID,
                        ItemID = model.SuperviseID,
                        ItemType = 事项类型.专项交办,
                        LeadUnit = o["LeadUnit"].ToString(),
                        CooperativeUnit = o["CooperativeUnit"].ToString(),
                        ReportLimit = DateTime.Parse(o["ReportLimit"].ToString()),
                        CompleteLimit = DateTime.Parse(o["CompleteLimit"].ToString()),
                        FeedbackLoop = (进展反馈周期)loop,
                        Days = int.Parse(o["Days"].ToString()),
                        Instime = DateTime.Now,
                        EmployeeCode = WxUser.LogonInfo.EmployeeCode,
                        UnitCode = WxUser.LogonInfo.UnitCode,
                        IsReport = model.IsReport
                    };
                    ctx.Yqd_Assign.Add(m);
                    ret = ctx.SaveChanges();
                    if (ret > 0)
                    {
                        var TaskName = "";
                        var task = ctx.Yqd_SpecialTask.FirstOrDefault(it => it.TaskID == model.TaskID);
                        if (task != null) TaskName = task.Name;
                        //关闭通知
                        //推送至主办单位
                        var msg = ddService.Notification(new List<string>(), model.TaskType.ToString(), model.TaskID.ToString(), "任务名称: " + TaskName, $"{WxUser.LogonInfo.UnitName}({WxUser.LogonInfo.Name})现予以交办，请及时办理！", pushStep: 推送流程.交办, unitCode: o["LeadUnit"].ToString(), superId: model.SuperviseID);
                        Logs.Warning<WxMySuperviseController>(WxUser.LogonInfo.Name + "发了" + model.TaskType.ToString() + "工作通知，返回值：" + msg);
                        TaskLogService.AddLog(model.SuperviseID, "填写了责任清单和时间清单", true);
                    }
                }
            }
            return this.ToJson(new
            {
                success = true,
                ret
            });
        }
        /// <summary>
        /// 更新督查
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [User]
        public IActionResult UpdateSupervise(Yqd_SpecialSupervise model)
        {
            var assign = ctx.Yqd_SpecialSupervise.Where(x => x.SuperviseID == model.SuperviseID && x.TaskID == model.TaskID).SingleOrDefault();
            if (assign == null)
            {
                return this.ToJson(new
                {
                    success = false,
                    ret = 0,
                    msg = "交办任务不存在"
                });
            }
            assign.Status = model.Status;
            var ret = ctx.SaveChanges();
            if (ret > 0)
            {
            }
            return this.ToJson(new
            {
                success = true,
                ret
            });
        }
        /// <summary>
        /// 获取督查单号
        /// </summary>
        private string GetSuperviseNo(int TaskID, 专项类型 TaskType)
        {
            var sno = DateTime.Now.Year.ToString();
            var rs = ctx.Yqd_SpecialSupervise.Where(it => !it.IsDel && it.TaskID == TaskID && it.TaskType == TaskType && it.SNo.Substring(0, 4) == sno).OrderByDescending(it => it.SNo);
            if (!rs.Any()) sno += "0001";
            else sno += (int.Parse(rs.First().SNo.Substring(4)) + 1).ToString("0000");
            return sno;
        }

        /// <summary>
        /// 修改专项督查
        /// </summary>
        /// <returns></returns>
        [User]
        public IActionResult Edit(Yqd_SpecialSupervise model)
        {
            var s = ctx.Yqd_SpecialSupervise.FirstOrDefault(it => it.SuperviseID == model.SuperviseID);
            if (s != null)
            {
                s.TemplateData = model.TemplateData;
                s.Photos = model.Photos;
                s.Standards = model.Standards;
                s.Problem = model.Problem;
            }
            var ret = ctx.SaveChanges();
            if (ret > 0)
            {
                TaskLogService.AddLog(model.SuperviseID, "修改了专项交办内容。", true);
            }
            return this.ToJson(new
            {
                success = true,
                ret
            });
        }

        [User]
        public ActionResult GetUnTaskCount()
        {
            var TaskID = Form.GetLong("TaskID");
            var TaskType = Form.GetInt("TaskType", 0);
            var IsDc = Form.GetBool("IsDc", true);
            var year = Form.GetInt("Year");
            int SchemeCount = 0;
            int ProgressCount = 0;
            int ReportCount = 0;
            int waitSchemeCount = 0;
            int waitProgressCount = 0;
            int waitReportCount = 0;
            string sql = "";
            //if (IsDc)
            //{
            //    sql += $" and [SuperviseID] in(select ItemID from Yqd_Assign where ItemType={(int)事项类型.专项交办}) ";
            //}
            if (year > 0)
            {
                sql = " and year(Instime)=" + year;
            }

            if (TaskID > 0)
            {
                SchemeCount = ctx.Database.SqlQuery<int>("select count(*) from Yqd_SpecialSupervise where IsArchive=0 and isDel=0 and isFinish=0 " + sql + " and [TaskID]=" + TaskID + " and [TaskType]=" + TaskType + " and ([SuperviseID] in(select ItemID from Yqd_Scheme where isDel=0 and ItemType=" + (int)事项类型.专项交办 + " and [CheckStatus]=" + (int)审核状态.待审 + "))").First();

                ProgressCount = ctx.Database.SqlQuery<int>("select count(*) from Yqd_SpecialSupervise where IsArchive=0 and isDel=0 and isFinish=0 " + sql + " and [TaskID]=" + TaskID + " and [TaskType]=" + TaskType + " and [SuperviseID] in(select ItemID from Yqd_PlanProgress where isDel=0 and ItemType=" + (int)事项类型.专项交办 + " and [CheckStatus]=" + (int)审核状态.待审 + " and AuditStatus=0)").First();

                ReportCount = ctx.Database.SqlQuery<int>("select count(*) from Yqd_SpecialSupervise where IsArchive=0 and isDel=0 and isFinish=0 " + sql + " and [TaskID]=" + TaskID + "  and [TaskType]=" + TaskType + " and [SuperviseID] in(select ItemID from Yqd_FinishReport where isDel=0 and ItemType=" + (int)事项类型.专项交办 + " and [CheckStatus]=" + (int)审核状态.待审 + ")").First();

                waitSchemeCount = SchemeCount;
                waitProgressCount = ProgressCount;
                waitReportCount = ReportCount;
            }
            else
            {
                SchemeCount = ctx.Database.SqlQuery<int>("select count(*) from Yqd_SpecialSupervise where IsArchive=0 and isDel=0 and isFinish=0 " + sql + " and [TaskType]=" + TaskType + " and ([SuperviseID] in(select ItemID from Yqd_Scheme where isDel=0 and ItemType=" + (int)事项类型.专项交办 + " and [CheckStatus]=" + (int)审核状态.待审 + "))").First();

                ProgressCount = ctx.Database.SqlQuery<int>("select count(*) from Yqd_SpecialSupervise where IsArchive=0 and isDel=0 and isFinish=0 " + sql + " and [TaskType]=" + TaskType + " and [SuperviseID] in(select ItemID from Yqd_PlanProgress where isDel=0 and ItemType=" + (int)事项类型.专项交办 + " and [CheckStatus]=" + (int)审核状态.待审 + " and AuditStatus=0)").First();

                ReportCount = ctx.Database.SqlQuery<int>("select count(*) from Yqd_SpecialSupervise where IsArchive=0 and isDel=0 and isFinish=0 " + sql + " and [TaskType]=" + TaskType + " and [SuperviseID] in(select ItemID from Yqd_FinishReport where isDel=0 and ItemType=" + (int)事项类型.专项交办 + " and [CheckStatus]=" + (int)审核状态.待审 + ")").First();

                waitSchemeCount = SchemeCount;
                waitProgressCount = ProgressCount;
                waitReportCount = ReportCount;
            }

            return this.ToJson(new
            {
                success = true,
                SchemeCount,
                ProgressCount,
                ReportCount,
                waitSchemeCount,
                waitProgressCount,
                waitReportCount
            });
        }

        [User]
        public ActionResult UpdateEvaluate()
        {
            var SuperviseID = Form.GetInt("SuperviseID");
            var Evaluate = Form.GetString("Evaluate");
            var ret = ctx.Database.ExecuteSql("update Yqd_SpecialSupervise set Evaluate={1} where SuperviseID={0};", SuperviseID, Evaluate);
            if (ret > 0)
            {
                var s = ctx.Yqd_SpecialSupervise.FirstOrDefault(it => it.SuperviseID == SuperviseID);
                if (s != null)
                    TaskLogService.AddLog(s.SuperviseID, "提交了专项评价。", true);
            }
            return this.ToJson(new
            {
                success = true,
                ret
            });
        }

        [User]
        public ActionResult Delete()
        {
            var l = WxUser.LogonInfo;
            if (!l.Role.Contains(角色类型.管理员))
            {
                return this.ToJson(new
                {
                    success = false,
                    msg = "无权限删除"
                });
            }
            var SuperviseID = Form.GetInt("SuperviseID");
            //;delete from Yqd_Assign where ItemID={0} and ItemType={1};
            var ret = ctx.Database.ExecuteSql("update Yqd_SpecialSupervise set isDel=1 where SuperviseID={0}", SuperviseID);
            if (ret > 0)
            {
                TaskLogService.AddLog(SuperviseID, "删除了专项交办", true);
            }
            return this.ToJson(new
            {
                success = true,
                ret
            });
        }
    }
}